package com.qf.commons.sentinel.config.exception;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.qf.data.base.r.Codes;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;

/**
 * 网关层 sentinel异常的处理
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
public class GatewaySentinelExceptionHandler implements BlockRequestHandler {

    @PostConstruct
    public void init(){
        //设置网关层的异常处理器
        GatewayCallbackManager.setBlockHandler(this);
    }

    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable t) {
        R rs = null;

        if (t instanceof FlowException) {
            //限流异常
            rs = Rs.createFail(Codes.REQUEST_TO_MANY);
        } else if (t instanceof DegradeException) {
            //降级异常
            rs = Rs.createFail(Codes.SERVICE_DEGRADE);
        }

        return ServerResponse
                .status(Codes.FAIL.getCode())
                .bodyValue(rs);
    }
}
